/**
 *   sci4j - Java library for scientific computation.
 *
 *   Copyright (C) 2010 Inaki Ortiz de Landaluce
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package org.sci4j.imaging.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;

public class StringUtils {

	public static String decode(byte[] b, String charsetName) throws UnsupportedCharsetException, CharacterCodingException {
		Charset charset = null;
		try {
			charset = Charset.forName(charsetName);			
		} catch (IllegalCharsetNameException e) {
			throw new UnsupportedCharsetException(charsetName);
		} catch (IllegalArgumentException e) {
			throw new UnsupportedCharsetException(charsetName);
		}
		CharsetDecoder decoder = charset.newDecoder();
		return decoder.decode(ByteBuffer.wrap(b)).toString();
	}
	
	public static byte[] encode(String s, String charsetName) throws UnsupportedCharsetException, CharacterCodingException {
		Charset charset = null;
		try {
			charset = Charset.forName(charsetName);			
		} catch (IllegalCharsetNameException e) {
			throw new UnsupportedCharsetException(charsetName);
		} catch (IllegalArgumentException e) {
			throw new UnsupportedCharsetException(charsetName);
		}
		CharsetEncoder encoder = charset.newEncoder();
		return encoder.encode(CharBuffer.wrap(s.toCharArray())).array();
	}
}
